package com.rtsapp.version.builder.utils;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.PutObjectRequest;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;


public class S3PutUtil implements IPutFile {

    private final ClientConfiguration clientConfig = new ClientConfiguration();

    private Element s3;

    private Element getRoot() {
        if (s3 == null) {
            try {
                SAXReader saxReader = new SAXReader();
                Document dom = saxReader.read(new File("cfg/cdn.xml"));
                s3 = dom.getRootElement().element("s3");

                clientConfig.setProtocol(Protocol.HTTP);
                clientConfig.setSocketTimeout(100000);
                clientConfig.setConnectionTimeout(20000);
                clientConfig.setMaxErrorRetry(5);

            } catch (DocumentException e) {
                e.printStackTrace();
            }
        }
        return s3;
    }

    private AmazonS3 getNewConnection() {

        getRoot();

        AWSCredentials credentials = new BasicAWSCredentials(s3.element("accessKeyID").attributeValue("value"), s3.element("accessKeySecret").attributeValue("value"));
        AmazonS3 connection = new AmazonS3Client(credentials, clientConfig);
        connection.setEndpoint(s3.element("endpoint").attributeValue("value"));
        return connection;
    }

    public boolean putFiles(String keyPrefix, String pathPrefix, String path) {

        AmazonS3 connection = getNewConnection();

        ObjectListing objects = connection.listObjects(s3.element("bucketName").attributeValue("value"), keyPrefix + path);

        if (objects != null && objects.getObjectSummaries().size() > 0)//判断是否已上传
        {
            return false;
        }

        PutObjectRequest uploadRequest = new PutObjectRequest(s3.element("bucketName").attributeValue("value"), keyPrefix + path, new File(pathPrefix + path));
        uploadRequest.setCannedAcl(CannedAccessControlList.PublicRead);
        connection.putObject(uploadRequest);
        return true;
    }
}
